package com.demo.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 * Jackson配置类，用于处理时间格式反序列化
 */
@Configuration
public class JacksonConfig {

    /**
     * 自定义LocalDateTime反序列化器
     */
    public static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        
        private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        
        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            String dateTimeString = p.getText();
            if (dateTimeString == null || dateTimeString.trim().isEmpty()) {
                return null;
            }
            
            try {
                // 尝试解析 "yyyy-MM-dd HH:mm:ss" 格式
                return LocalDateTime.parse(dateTimeString, FORMATTER);
            } catch (DateTimeParseException e) {
                try {
                    // 如果失败，尝试解析 ISO 格式 "yyyy-MM-ddTHH:mm:ss"
                    return LocalDateTime.parse(dateTimeString);
                } catch (DateTimeParseException e2) {
                    throw new IOException("无法解析时间格式: " + dateTimeString, e2);
                }
            }
        }
    }

    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        
        // 注册Java时间模块
        mapper.registerModule(new JavaTimeModule());
        
        // 创建自定义模块
        SimpleModule customModule = new SimpleModule();
        customModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
        mapper.registerModule(customModule);
        
        return mapper;
    }
}

















